import { getProfile, getUserId } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    // 优先从本地储存获取数据
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    upataToken(state, token) {
      state.token = token
      // 将token 封装到本地
      setToken(token)
    },
    delToken(state) {
      state.token = ''
      // 清空token
      removeToken()
    },
    upateUserInfo(state, info) {
      state.userInfo = info
    },
    // 清空信息
    delUser(state) {
      state.userInfo = {}
    }
  },
  // 数据异步更新
  actions: {
    async getUserInfo(context) {
      try {
        const res = await getProfile()
        console.log(res)
        const info = await getUserId(res.data.userId)
        context.commit('upateUserInfo', { ...res.data, ...info.data })
      } catch (error) {
        console.log(error)
      }
    },
    logout(context) {
      context.commit('delToken')
      context.commit('delUser')
    }
  }
}

